import 'package:cached_network_image/cached_network_image.dart';
import 'package:calendar_date_picker2/calendar_date_picker2.dart';
import 'package:catguard/language.dart';
import 'package:common_utils/common_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:catguard/routers/routers.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:flutter_widget_from_html_core/flutter_widget_from_html_core.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import '../config/config.dart';
import '../generated/assets.dart';
import '../utils/edit_focus_util.dart';

///
/// dialog管理器
///
class DialogManager {
  ///===========================================================默认样式的dialog
  static showDialog(String desc, Function() onConfirm,
      {String title = '', String okText = '确定', String canText = '取消', bool isSingle = false}) {
    Widget widget = Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Container(
          width: 600.w,
          decoration: BoxDecoration(
            color: Config.colorBg,
            borderRadius: BorderRadius.circular(30.w),
          ),
          child: Column(
            children: [
              Visibility(
                visible: title.isNotEmpty,
                child: Container(
                  margin: EdgeInsets.only(top: 30.w),
                  padding: EdgeInsets.symmetric(horizontal: 26.w),
                  child: Text(
                    title,
                    style: TextStyle(fontSize: Config.textSizeTitle.sp, color: Config.colorText1),
                  ),
                ),
              ),
              Container(
                margin: EdgeInsets.only(top: 35.w, bottom: 35.w),
                padding: EdgeInsets.symmetric(horizontal: 26.w),
                child: Text(
                  desc,
                  textAlign: TextAlign.center,
                  style: TextStyle(fontSize: Config.textSizeSubTitle.sp, color: Config.colorText1),
                ),
              ),
              Divider(
                height: 2.w,
                thickness: 1.5.w,
                color: Config.colorDivider,
              ),
              Container(
                height: 98.w,
                child: Row(
                  children: [
                    Expanded(
                      child: InkWell(
                        onTap: () {
                          Get.back();
                        },
                        child: Text(
                          canText,
                          style: TextStyle(
                              fontSize: Config.textSizeSubTitle.sp, color: Config.colorText3),
                          textAlign: TextAlign.center,
                        ),
                      ),
                    ),
                    Visibility(
                      visible: !isSingle,
                      child: Container(
                        width: 1.5.w,
                        height: 94.w,
                        color: Config.colorDivider,
                      ),
                    ),
                    Visibility(
                      visible: !isSingle,
                      child: Expanded(
                        child: InkWell(
                          onTap: () {
                            Get.back();
                            onConfirm();
                          },
                          child: Text(
                            okText,
                            style: TextStyle(
                                fontSize: Config.textSizeSubTitle.sp, color: Config.colorMain),
                            textAlign: TextAlign.center,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        )
      ],
    );
    Get.dialog(widget);
  }

  ///===========================================================默认样式的dialog-带一个输入框
  static showEditDialog(String desc, Function(String text) onConfirm,
      {String title = '',
      String okText = '确定',
      String canText = '取消',
      bool isSingle = false,
      String hint = ""}) {
    String inputText = "";
    Widget widget = Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Container(
          width: 600.w,
          decoration: BoxDecoration(
            color: Config.colorBg,
            borderRadius: BorderRadius.circular(30.w),
          ),
          child: Column(
            children: [
              Visibility(
                visible: title.isNotEmpty,
                child: Container(
                  margin: EdgeInsets.only(top: 30.w),
                  padding: EdgeInsets.symmetric(horizontal: 26.w),
                  child: Text(
                    title,
                    style: TextStyle(fontSize: Config.textSizeTitle.sp, color: Config.colorText1),
                  ),
                ),
              ),
              Container(
                margin: EdgeInsets.only(top: 35.w, bottom: 35.w),
                padding: EdgeInsets.symmetric(horizontal: 26.w),
                child: Text(
                  desc,
                  style: TextStyle(fontSize: Config.textSizeSubTitle.sp, color: Config.colorText1),
                ),
              ),
              Container(
                height: 80.w,
                margin: EdgeInsets.only(top: 0.w, bottom: 42.w, left: 40.w, right: 40.w),
                padding: EdgeInsets.symmetric(horizontal: 26.w),
                decoration: BoxDecoration(
                    border: Border.all(color: Config.colorMain.withOpacity(0.5), width: 1.5.w),
                    borderRadius: BorderRadius.circular(22.w),
                    color: Config.colorMain.withOpacity(0.15)),
                alignment: Alignment.center,
                child: TextField(
                  keyboardType: TextInputType.text,
                  textAlign: TextAlign.left,
                  maxLength: 40,
                  maxLines: 1,
                  cursorColor: Config.colorMain,
                  onChanged: (value) {
                    inputText = value;
                  },
                  onTap: () {},
                  enabled: true,
                  controller: TextEditingController(text: hint),
                  style: TextStyle(fontSize: Config.textSizeContent.sp, color: Config.colorText1),
                  decoration: InputDecoration(
                    isDense: true,
                    // 紧凑模式
                    hintText: "",
                    counterText: '',
                    hintStyle:
                        TextStyle(fontSize: Config.textSizeContent.sp, color: Config.colorText3),
                    border: InputBorder.none,
                    filled: false,
                    prefixIcon: null,
                    contentPadding: EdgeInsets.symmetric(vertical: 0.w, horizontal: 0.w),
                  ),
                ),
              ),
              Divider(
                height: 2.w,
                thickness: 1.5.w,
                color: Config.colorDivider,
              ),
              Container(
                height: 98.w,
                child: Row(
                  children: [
                    Expanded(
                      child: InkWell(
                        onTap: () {
                          Get.back();
                        },
                        child: Text(
                          canText,
                          style: TextStyle(
                              fontSize: Config.textSizeSubTitle.sp, color: Config.colorText3),
                          textAlign: TextAlign.center,
                        ),
                      ),
                    ),
                    Visibility(
                      visible: !isSingle,
                      child: Container(
                        width: 1.5.w,
                        height: 94.w,
                        color: Config.colorDivider,
                      ),
                    ),
                    Visibility(
                      visible: !isSingle,
                      child: Expanded(
                        child: InkWell(
                          onTap: () {
                            Get.back();
                            onConfirm(inputText);
                          },
                          child: Text(
                            okText,
                            style: TextStyle(
                                fontSize: Config.textSizeSubTitle.sp, color: Config.colorMain),
                            textAlign: TextAlign.center,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        )
      ],
    );
    Get.dialog(widget, barrierDismissible: false);
  }

  ///===========================================================一个通用的底部弹出列表选项
  static getListItem(int index, String str, Function func) {
    return InkWell(
      onTap: () {
        func(index);
      },
      child: Container(
        decoration: BoxDecoration(
          border: Border(
            bottom: BorderSide(color: Config.colorDivider, width: 1.2.w),
          ),
        ),
        width: double.infinity,
        height: 108.w,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Opacity(
              opacity: 0,
              child: SizedBox(
                width: 50.w,
              ),
            ),
            Text(
              str,
              softWrap: false,
              style: TextStyle(
                  color: index == currentBottomMenu ? Config.colorMain : Config.colorText1,
                  fontSize: Config.textSizeSubTitle.sp,
                  fontWeight: FontWeight.w500),
            ),
            Opacity(
              opacity: index == currentBottomMenu ? 1 : 0,
              child: Icon(
                Icons.check,
                size: 50.w,
                color: Config.colorMain,
              ),
            ),
          ],
        ),
      ),
    );
  }

  static int currentBottomMenu = 0;

  static showBottomMenu(
      BuildContext context, List<String> datas, int defaultPosition, Function func) {
    currentBottomMenu = defaultPosition;
    return Get.bottomSheet(Column(
      mainAxisAlignment: MainAxisAlignment.end,
      children: [
        StatefulBuilder(builder: (BuildContext context, StateSetter setState) {
          return Container(
            margin: EdgeInsets.only(left: 35.w, right: 35.w),
            decoration: BoxDecoration(
              color: Config.colorBg2,
              borderRadius: BorderRadius.circular(Config.roundBig.w),
            ),
            height: datas.length <= 6 ? (datas.length * 108.w) : (6 * 108.w),
            child: ListView.builder(
              padding: EdgeInsets.symmetric(horizontal: 35.w),
              itemCount: datas.length,
              shrinkWrap: true,
              scrollDirection: Axis.vertical,
              physics: const ClampingScrollPhysics(),
              itemBuilder: (BuildContext context, int index) {
                return getListItem(index, datas[index], (index) {
                  currentBottomMenu = index;
                  setState(() {});
                });
              },
            ),
          );
        }),
        SizedBox(
          height: 30.w,
        ),
        Container(
          height: 108.w,
          margin: EdgeInsets.only(left: 35.w, right: 35.w),
          decoration: BoxDecoration(
            color: Config.colorBg2,
            borderRadius: BorderRadius.circular(Config.roundBig.w),
          ),
          child: Row(
            children: [
              Expanded(
                child: InkWell(
                  onTap: () {
                    Get.back();
                  },
                  child: Container(
                    height: 108.w,
                    alignment: Alignment.center,
                    child: Text(
                      '取消',
                      textAlign: TextAlign.center,
                      style: TextStyle(
                          color: Config.colorText3,
                          fontSize: Config.textSizeSubTitle.sp,
                          fontWeight: FontWeight.w500),
                    ),
                  ),
                ),
              ),
              Container(
                width: 1.2.w,
                margin: EdgeInsets.symmetric(vertical: 10.w),
                color: Config.colorDivider,
              ),
              Expanded(
                child: InkWell(
                  onTap: () {
                    func(currentBottomMenu);
                    Get.back();
                  },
                  child: Container(
                    height: 108.w,
                    alignment: Alignment.center,
                    child: Text(
                      '确认',
                      textAlign: TextAlign.center,
                      style: TextStyle(
                          color: Config.colorMain,
                          fontSize: Config.textSizeSubTitle.sp,
                          fontWeight: FontWeight.w500),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
        SizedBox(
          height: 40.w,
        ),
      ],
    ));
  }

  ///===========================================================一个通用的底部弹出日期选择
  static showBottomDatePop(BuildContext context, Function func) {
    List<DateTime?> singleDatePickerValueWithDefaultValue = [
      DateTime.now(),
    ];
    final config = CalendarDatePicker2Config(
      selectedDayHighlightColor: Config.colorMain,
      weekdayLabels: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
      weekdayLabelTextStyle: const TextStyle(
        color: Config.colorText1,
        fontWeight: FontWeight.bold,
      ),
      firstDayOfWeek: 1,
      disableMonthPicker: true,
      controlsHeight: 50,
      dayMaxWidth: 25,
      animateToDisplayedMonthDate: true,
      controlsTextStyle: TextStyle(
        color: Config.colorText1,
        fontSize: Config.textSizeTitle.w,
        fontWeight: FontWeight.w600,
      ),
      dayTextStyle: const TextStyle(
        color: Config.colorText1,
        fontWeight: FontWeight.w400,
      ),
      disabledDayTextStyle: const TextStyle(
        color: Config.colorText3,
      ),
      centerAlignModePicker: true,
      useAbbrLabelForMonthModePicker: true,
      modePickersGap: 0,
      modePickerTextHandler: ({required monthDate, isMonthPicker}) {
        if (isMonthPicker ?? false) {
          // Custom month picker text
          return '${getLocaleShortMonthFormat(const Locale('en')).format(monthDate)} C';
        }
        return null;
      },
      firstDate:
          DateTime(DateTime.now().year - 2, DateTime.now().month - 1, DateTime.now().day - 5),
      lastDate:
          DateTime(DateTime.now().year + 3, DateTime.now().month + 2, DateTime.now().day + 10),
      // selectableDayPredicate: (day) =>
      // !day
      //     .difference(DateTime.now().add(const Duration(days: 3)))
      //     .isNegative &&
      //     day.isBefore(DateTime.now().add(const Duration(days: 30))),
    );

    String currentDateStr =
        DateFormat('yyyy-MM-dd', 'zh_CN').format(singleDatePickerValueWithDefaultValue.first!);

    return Get.bottomSheet(Column(
      mainAxisAlignment: MainAxisAlignment.end,
      children: [
        Container(
          margin: EdgeInsets.only(left: 35.w, right: 35.w),
          padding: EdgeInsets.only(bottom: 10.w, top: 10.w),
          decoration: BoxDecoration(
            color: Config.colorBg2,
            borderRadius: BorderRadius.circular(Config.roundBig.w),
          ),
          child: CalendarDatePicker2(
            config: config,
            displayedMonthDate: singleDatePickerValueWithDefaultValue.first,
            value: singleDatePickerValueWithDefaultValue,
            onValueChanged: (dates) {
              currentDateStr = DateFormat('yyyy-MM-dd', 'zh_CN').format(dates.first);
            },
          ),
        ),
        SizedBox(
          height: 30.w,
        ),
        Container(
          height: 108.w,
          margin: EdgeInsets.only(left: 35.w, right: 35.w),
          decoration: BoxDecoration(
            color: Config.colorBg2,
            borderRadius: BorderRadius.circular(Config.roundBig.w),
          ),
          child: Row(
            children: [
              Expanded(
                child: InkWell(
                  onTap: () {
                    Get.back();
                  },
                  child: Container(
                    height: 108.w,
                    alignment: Alignment.center,
                    child: Text(
                      '取消',
                      textAlign: TextAlign.center,
                      style: TextStyle(
                          color: Config.colorText3,
                          fontSize: Config.textSizeSubTitle.sp,
                          fontWeight: FontWeight.w500),
                    ),
                  ),
                ),
              ),
              Container(
                width: 1.2.w,
                margin: EdgeInsets.symmetric(vertical: 10.w),
                color: Config.colorDivider,
              ),
              Expanded(
                child: InkWell(
                  onTap: () {
                    func(currentDateStr);
                    Get.back();
                  },
                  child: Container(
                    height: 108.w,
                    alignment: Alignment.center,
                    child: Text(
                      '确认',
                      textAlign: TextAlign.center,
                      style: TextStyle(
                          color: Config.colorMain,
                          fontSize: Config.textSizeSubTitle.sp,
                          fontWeight: FontWeight.w500),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
        SizedBox(
          height: 40.w,
        ),
      ],
    ));
  }

  ///============================================================升级弹窗
  static appUpdateDialog(BuildContext context, String content, Function() fun) async {
    Widget widget = Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Container(
          width: 590.w,
          decoration: BoxDecoration(
            color: Config.colorBg2,
            borderRadius: BorderRadius.circular(22.w),
          ),
          child: Column(
            children: [
              SizedBox(height: 35.w),
              SvgPicture.asset(Assets.iconsIconUpdateRocket, width: 100.w, height: 100.w),
              Container(
                margin: EdgeInsets.only(top: 20.w),
                padding: EdgeInsets.symmetric(horizontal: 20.w),
                child: Text(
                  " LanguageMsg.dialogUpdateTitle.tr",
                  style: TextStyle(fontSize: Config.textSizeSubTitle.sp, color: Config.colorText1),
                ),
              ),
              Container(
                width: 460.w,
                margin: EdgeInsets.only(top: 34.w, bottom: 48.w),
                padding: EdgeInsets.symmetric(horizontal: 10.w),
                child: Text(
                  content,
                  style: TextStyle(fontSize: Config.textSizeContent.sp, color: Config.colorText1),
                ),
              ),
              GestureDetector(
                onTap: () {
                  fun();
                  Get.back();
                },
                child: Container(
                  padding: EdgeInsets.symmetric(horizontal: 22.w),
                  height: 92.w,
                  width: 460.w,
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.all(Radius.circular(58.w)),
                    gradient: const LinearGradient(
                      begin: Alignment.centerLeft,
                      end: Alignment.centerRight,
                      colors: [Color(0xFFA0FF5C), Color(0xFFC1FB93)],
                    ),
                  ),
                  child: Text(
                    "LanguageMsg.dialogUpdateNow.tr",
                    style: TextStyle(color: Config.colorBg, fontSize: 32.sp),
                  ),
                ),
              ),
              Container(
                height: 70.w,
                margin: EdgeInsets.only(bottom: 20.w, top: 10.w),
                child: Row(
                  children: [
                    Expanded(
                      child: InkWell(
                        onTap: () {
                          Get.back();
                        },
                        child: Text(
                          "LanguageMsg.dialogUpdateCancel.tr",
                          style: TextStyle(
                              fontSize: Config.textSizeContent.sp, color: Config.colorText3),
                          textAlign: TextAlign.center,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        )
      ],
    );
    Get.dialog(widget);
  }
}
